package com.dwy2002.common.utils;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Hash加密密码工具类
 *
 * @author 杜伟毅
 * @version 1.0
 * @since 2024/11/02
 */
@Slf4j
public class HashUtils {
    /**
     * 生成密码的哈希值
     *
     * @param password 前端传的密码
     * @return String 返回一串hash字符串
     * @author 杜伟毅
     * @since 2023/10/5 0005 12:28
     */
    public static String generateHash(String password) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
            byte[] hashBytes = messageDigest.digest(password.getBytes(StandardCharsets.UTF_8));
            StringBuilder stringBuilder = new StringBuilder();
            for (byte hashByte : hashBytes) {
                stringBuilder.append(Integer.toString((hashByte & 0xff) + 0x100, 16).substring(1));
            }
            return stringBuilder.toString();
        } catch (NoSuchAlgorithmException e) {
//            log.error(String.valueOf(e));

            return null;
        }
    }

    /**
     * 验证密码是否匹配
     *
     * @param password   前端传过来的的密码
     * @param dbPassword 数据库的密码
     * @return true：两边密码正确 ， false：两边密码不正确
     * @author 杜伟毅
     * @since 2023/10/5 0005 12:25
     */
    public static boolean verifyPassword(String password, String dbPassword) {
        if (StringUtils.isEmpty(password) || StringUtils.isEmpty(dbPassword)) {
            return false;
        }
        String passwordHash = generateHash(password);
        return passwordHash.equals(dbPassword);
    }
}
